package com.youbug.common.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.youbug.common.constant.MenuConstant;
import com.youbug.common.constant.SystemConstant;
import com.youbug.common.exception.AuthException;
import com.youbug.common.util.UserUtils;
import com.youbug.system.entity.Menu;
import com.youbug.common.exception.NoLoginException;
import com.youbug.system.entity.User;
import com.youbug.system.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private IMenuService menuService;

    private List<String> authProtectedMethods;

    private Long updateTime;

    private List<String> loginAccess = Arrays.asList("common","useDic");// 登录后可以访问的controller

    private List<String> noLoginAccess = Arrays.asList("portal","login","logout","client","keepalive","kaptcha","error","index");// 不登录可以访问的controller

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        sholdUpdateAuthedMethods();

        String requestURI = request.getRequestURI();

        String[] pathSplit = requestURI.split("/");

        String controllerPath;
        String methodPath = "";

        if(pathSplit.length == 2){
            controllerPath = pathSplit[1];
        }else{
            controllerPath = pathSplit[1];
            methodPath = pathSplit[2];
        }

        if(noLoginAccess.contains(controllerPath)){
            return true;
        }else{
            Object attribute = request.getSession().getAttribute(SystemConstant.PERMISSION);
            Map<String,List<String>> permissionMap = null;
            if(attribute instanceof Map){
                permissionMap = (Map<String,List<String>>) attribute;
            }
            if(permissionMap == null){
                if(noLoginAccess.contains(controllerPath)){
                    return true;
                }
                throw new NoLoginException("登录超时或未登录，请重新登录");
            }else{
                if(loginAccess.contains(controllerPath)){
                    return true;
                }
                if(permissionMap.keySet().contains(controllerPath)){

                    List<String> authedMethods = permissionMap.get(controllerPath);

                    if(!CollectionUtils.isEmpty(authedMethods)){
                        if(authProtectedMethods.contains(methodPath)){// 该方法是否被权限控制
                            boolean contains = authedMethods.contains(methodPath);

                            if(!contains){// 判断具体方法的权限
                                throw new AuthException("缺少访问权限");
                            }
                        }
                    }
                    Object o = request.getSession().getAttribute(SystemConstant.CURRENT_USER);
                    if(!ObjectUtils.isEmpty(o) && o instanceof User){
                        UserUtils.setCurrentUser((User)o);
                    }
                    return true;
                }else{
                    throw new AuthException("缺少访问权限");
                }
            }
        }
    }

    private void sholdUpdateAuthedMethods() {
        if(CollectionUtils.isEmpty(authProtectedMethods) || (System.currentTimeMillis() - updateTime) > 300*1000){
            updateTime = System.currentTimeMillis();
            List<Menu> menus = menuService.list(new QueryWrapper<Menu>().in("node_type", MenuConstant.BTN));
            authProtectedMethods = menus.stream().map(menu -> menu.getPath().replace("/", "")).collect(Collectors.toList());
        }
    }
}
